package com.sansecy.customview.view.progress;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.sansecy.customview.BuildConfig;
import com.sansecy.customview.R;

public class CircleProgress extends View {

    private static final String TAG = CircleProgress.class.getSimpleName();

    private Context mContext;
    //默认大小
    private int mDefaultSize;
    //是否开启抗锯齿
    private boolean antiAlias;

    private float mValue;
    private float mMaxValue;
    private int mPrecision;

    //绘制圆弧
    private Paint mArcPaint;
    private Paint mArcBgPaint;
    private float mArcWidth;
    private float mStartAngle, mSweepAngle;
    private RectF mRectF;
    //当前进度，[0.0f,1.0f]
    private float mPercent;
    //动画时间
    private long mAnimTime;
    //属性动画
    private ValueAnimator mAnimator;

    //绘制背景圆弧
    private Paint mDottedLinePaint;
    private int mDottedLineColor;
    private int mArcColor;

    //圆心坐标，半径
    private Point mCenterPoint;
    private float mRadius;
    private float mTextOffsetPercentInRadius;

    private int mArcCenterX;
    // 内部虚线的外部半径
    private float mExternalDottedLineRadius;
    // 内部虚线的内部半径
    private float mInsideDottedLineRadius;

    // 线条数
    private int mDottedLineCount = 92;
    // 圆弧跟虚线之间的距离
    private int mLineDistance = 20;
    // 线条宽度
    private float mDottedLineWidth = 40;
    //是否使用渐变
    protected boolean useGradient = true;
    //前景色起始颜色
    private int foreStartColor;
    //前景色结束颜色
    private int foreEndColcor;
    private float mCircleSpace;
    private int mDottedLineBgColor;
    private float mMaxArcWidth;
    private int mArcBgColor;
    private float mDottedLineLength;

    public CircleProgress(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        mContext = context;
        mDefaultSize = dipToPx(mContext, 150);
        mAnimator = new ValueAnimator();
        mRectF = new RectF();
        mCenterPoint = new Point();
        initAttrs(attrs);
        initPaint();
        setValue(mValue);
    }

    private void initAttrs(AttributeSet attrs) {
        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar);

        antiAlias = typedArray.getBoolean(R.styleable.CircleProgressBar_antiAlias, true);


        mValue = typedArray.getFloat(R.styleable.CircleProgressBar_value, 50);
        mMaxValue = typedArray.getFloat(R.styleable.CircleProgressBar_maxValue, 50);
        //内容数值精度格式
        mPrecision = typedArray.getInt(R.styleable.CircleProgressBar_precision, 0);

        mArcWidth = typedArray.getDimension(R.styleable.CircleProgressBar_arcWidth, 15);
        mStartAngle = typedArray.getFloat(R.styleable.CircleProgressBar_startAngle, 270);
        mSweepAngle = typedArray.getFloat(R.styleable.CircleProgressBar_sweepAngle, 360);
        mCircleSpace = typedArray.getDimension(R.styleable.CircleProgressBar_circleSpace, 50);
        mDottedLineBgColor = typedArray.getColor(R.styleable.CircleProgressBar_dottedLineBgColor, Color.WHITE);
        mArcBgColor = typedArray.getColor(R.styleable.CircleProgressBar_arcBgColor, Color.BLACK);

        mDottedLineColor = typedArray.getColor(R.styleable.CircleProgressBar_dottedLineBgColor, Color.WHITE);
        mArcColor = typedArray.getColor(R.styleable.CircleProgressBar_arcColors, Color.RED);
        mTextOffsetPercentInRadius = typedArray.getFloat(R.styleable.CircleProgressBar_textOffsetPercentInRadius, 0.33f);
        mAnimTime = typedArray.getInt(R.styleable.CircleProgressBar_animTime, 1000);
        mDottedLineCount = typedArray.getInteger(R.styleable.CircleProgressBar_dottedLineCount, mDottedLineCount);
        mLineDistance = typedArray.getInteger(R.styleable.CircleProgressBar_lineDistance, mLineDistance);
        mDottedLineWidth = typedArray.getDimension(R.styleable.CircleProgressBar_dottedLineWidth, mDottedLineWidth);
        mDottedLineLength = typedArray.getDimension(R.styleable.CircleProgressBar_dottedLineLength, mDottedLineWidth);
        foreStartColor = typedArray.getColor(R.styleable.CircleProgressBar_foreStartColor, Color.BLUE);
        foreEndColcor = typedArray.getColor(R.styleable.CircleProgressBar_foreEndColor, Color.BLUE);
        typedArray.recycle();
    }

    private void initPaint() {
        //圆弧画笔
        mArcPaint = new Paint();
        mArcPaint.setAntiAlias(antiAlias);
        mArcPaint.setStyle(Paint.Style.STROKE);
        mArcPaint.setStrokeWidth(mArcWidth);
        mArcPaint.setStrokeCap(Paint.Cap.ROUND);

        //圆弧背景画笔
        mArcBgPaint = new Paint();
        mArcBgPaint.setAntiAlias(antiAlias);
        mArcBgPaint.setStyle(Paint.Style.STROKE);
        mArcBgPaint.setStrokeWidth(mArcWidth);
        mArcBgPaint.setStrokeCap(Paint.Cap.ROUND);
        mArcBgPaint.setColor(mArcBgColor);

        //外部虚线画笔
        mDottedLinePaint = new Paint();
        mDottedLinePaint.setAntiAlias(antiAlias);
        mDottedLinePaint.setColor(mDottedLineColor);
        mDottedLinePaint.setStyle(Paint.Style.STROKE);
        mDottedLinePaint.setStrokeWidth(mDottedLineWidth);
        mDottedLinePaint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(measureView(widthMeasureSpec, mDefaultSize),
                measureView(heightMeasureSpec, mDefaultSize));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mArcCenterX = (int) (w / 2.f);
//        Log.d(TAG, "onSizeChanged: w = " + w + "; h = " + h + "; oldw = " + oldw + "; oldh = " + oldh);
        //求圆弧和背景圆弧的最大宽度
        mMaxArcWidth = mArcWidth;
        Log.d(this.getClass().getSimpleName() + "-App", "onSizeChanged:mMaxArcWidth " + mMaxArcWidth);
        //求最小值作为实际值
//        int minSize = Math.min(w - getPaddingLeft() - getPaddingRight() - 2 * (int) mMaxArcWidth,
//                h - getPaddingTop() - getPaddingBottom() - 2 * (int) mMaxArcWidth);
        //减去圆弧的宽度，否则会造成部分圆弧绘制在外围

        //获取圆的相关参数
        mCenterPoint.x = w / 2;
        mCenterPoint.y = h / 2;
        //绘制圆弧的边界
        mRectF.left = getPaddingLeft();
        mRectF.top = getPaddingTop();
        mRectF.right = w - getPaddingRight();
        mRectF.bottom = h - getPaddingBottom();

        Log.d(this.getClass().getSimpleName() + "-App", "onSizeChanged:maxArcWidth " + mMaxArcWidth);
        Log.d(this.getClass().getSimpleName() + "-App", "onSizeChanged:w / 2 " + w / 2);

        if (useGradient) {
            LinearGradient gradient = new LinearGradient(0, 0, w, h, foreEndColcor, foreStartColor, Shader.TileMode.CLAMP);
            mArcPaint.setShader(gradient);
        } else {
            mArcPaint.setColor(mArcColor);
        }

//        Log.d(TAG, "onSizeChanged: 控件大小 = " + "(" + w + ", " + h + ")"
//                + "圆心坐标 = " + mCenterPoint.toString()
//                + ";圆半径 = " + mRadius
//                + ";圆的外接矩形 = " + mRectF.toString());

        // 虚线的外部半径
        mExternalDottedLineRadius = (int) (mRectF.width() / 2) - getPaddingLeft();
        // 虚线的内部半径
        mInsideDottedLineRadius = mExternalDottedLineRadius - mDottedLineLength;
        mRectF.left += (mCircleSpace + mMaxArcWidth);
        mRectF.top += (mCircleSpace + mMaxArcWidth);
        mRectF.right -= (mCircleSpace + mMaxArcWidth);
        mRectF.bottom -= (mCircleSpace + mMaxArcWidth);
    }

    private float getBaselineOffsetFromY(Paint paint) {
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        return ((Math.abs(fontMetrics.ascent) - fontMetrics.descent)) / 2;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawArc(mRectF, mStartAngle + 2, 265, false, mArcBgPaint);
        drawArc(canvas);
    }

    private void drawArc(Canvas canvas) {
        // 绘制背景圆弧
        // 从进度圆弧结束的地方开始重新绘制，优化性能
        canvas.save();
        float currentAngle = mSweepAngle * mPercent;
        // 360 * Math.PI / 180
        float evenryDegrees = (float) (2.0f * Math.PI / mDottedLineCount);
        float currentDegress = (float) ((currentAngle + 2) * Math.PI / 180);
//        float endDegress = (float) (225 * Math.PI / 180);
        float endDegress = (float) (270 * Math.PI / 180);
        canvas.rotate(mStartAngle, mCenterPoint.x, mCenterPoint.y);
        canvas.drawArc(mRectF, 2, currentAngle, false, mArcPaint);

        canvas.rotate(180 - mStartAngle + 45, mCenterPoint.x, mCenterPoint.y);

        for (int i = 0; i < mDottedLineCount; i++) {
            float degrees = i * evenryDegrees;
            if (degrees < currentDegress) {
                mDottedLinePaint.setColor(mDottedLineColor);
            } else {
                mDottedLinePaint.setColor(mDottedLineBgColor);
            }


            float startX = mArcCenterX + (float) Math.sin(degrees) * mInsideDottedLineRadius;
            float startY = mArcCenterX - (float) Math.cos(degrees) * mInsideDottedLineRadius;

            float stopX = mArcCenterX + (float) Math.sin(degrees) * mExternalDottedLineRadius;
            float stopY = mArcCenterX - (float) Math.cos(degrees) * mExternalDottedLineRadius;

            canvas.drawLine(startX, startY, stopX, stopY, mDottedLinePaint);
//            if (degrees > endDegress) {
//                float startXInternal = mArcCenterX + (float) Math.sin(degrees) * (mInsideDottedLineRadius - mArcWidth-10);
//                float startYInternal = mArcCenterX - (float) Math.cos(degrees) * (mInsideDottedLineRadius - mArcWidth-10);
//
//                float stopXInternal = mArcCenterX + (float) Math.sin(degrees) * (mExternalDottedLineRadius - mArcWidth - 35);
//                float stopYInternal = mArcCenterX - (float) Math.cos(degrees) * (mExternalDottedLineRadius - mArcWidth - 35);
//                canvas.drawLine(startXInternal, startYInternal, stopXInternal, stopYInternal, mDottedLinePaint);
//            }
        }

        // 第一个参数 oval 为 RectF 类型，即圆弧显示区域
        // startAngle 和 sweepAngle  均为 float 类型，分别表示圆弧起始角度和圆弧度数
        // 3点钟方向为0度，顺时针递增
        // 如果 startAngle < 0 或者 > 360,则相当于 startAngle % 360
        // useCenter:如果为True时，在绘制圆弧时将圆心包括在内，通常用来绘制扇形

        canvas.restore();
    }

    public boolean isAntiAlias() {
        return antiAlias;
    }

    public float getValue() {
        return mValue;
    }

    /**
     * 设置当前值
     *
     * @param value
     */
    public void setValue(float value) {
        if (value > mMaxValue) {
            value = mMaxValue;
        }
        float start = mPercent;
        float end = value / mMaxValue;
        startAnimator(start, end, mAnimTime);
    }

    private void startAnimator(float start, float end, long animTime) {
        mAnimator = ValueAnimator.ofFloat(start, end);
        mAnimator.setDuration(animTime);
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mPercent = (float) animation.getAnimatedValue();
                if (mUpdateListener != null) {
                    mUpdateListener.onPercentUpdate(mPercent);
                }
                mValue = mPercent * mMaxValue;
                if (BuildConfig.DEBUG) {
//                    Log.d(TAG, "onAnimationUpdate: percent = " + mPercent
//                            + ";currentAngle = " + (mSweepAngle * mPercent)
//                            + ";value = " + mValue);
                }
                invalidate();
            }
        });
        mAnimator.start();
    }

    public OnAnimationPercentUpdateListener mUpdateListener;

    public void setUpdateListener(OnAnimationPercentUpdateListener updateListener) {
        mUpdateListener = updateListener;
    }

    public interface OnAnimationPercentUpdateListener {
        void onPercentUpdate(float percent);
    }

    /**
     * 获取最大值
     *
     * @return
     */
    public float getMaxValue() {
        return mMaxValue;
    }

    /**
     * 设置最大值
     *
     * @param maxValue
     */
    public void setMaxValue(float maxValue) {
        mMaxValue = maxValue;
    }

    /**
     * 获取精度
     *
     * @return
     */
    public int getPrecision() {
        return mPrecision;
    }

    public void setPrecision(int precision) {
        mPrecision = precision;
    }

    public long getAnimTime() {
        return mAnimTime;
    }

    public void setAnimTime(long animTime) {
        mAnimTime = animTime;
    }

    /**
     * 重置
     */
    public void reset() {
        startAnimator(mPercent, 0.0f, 1000L);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        //释放资源
    }

    /**
     * 测量 View
     *
     * @param measureSpec
     * @param defaultSize View 的默认大小
     * @return
     */
    private static int measureView(int measureSpec, int defaultSize) {
        int result = defaultSize;
        int specMode = View.MeasureSpec.getMode(measureSpec);
        int specSize = View.MeasureSpec.getSize(measureSpec);

        if (specMode == View.MeasureSpec.EXACTLY) {
            result = specSize;
        } else if (specMode == View.MeasureSpec.AT_MOST) {
            result = Math.min(result, specSize);
        }
        return result;
    }

    /**
     * dip 转换成px
     *
     * @param dip
     * @return
     */
    public static int dipToPx(Context context, float dip) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1));
    }

    /**
     * 获取数值精度格式化字符串
     *
     * @param precision
     * @return
     */
    public static String getPrecisionFormat(int precision) {
        return "%." + precision + "f";
    }
}